package com.sopaths.crawler.task.handler;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.log4j.Logger;

import com.sopaths.contract.crawler.City;
import com.sopaths.contract.crawler.CrawlerTaskType;
import com.sopaths.crawler.tasks.CityCrawlerTask;
import com.sopaths.crawler.tasks.CrawlerTask;
import com.sopaths.crawler.tasks.SummaryTotalPageCrawlerTask;
import com.sopaths.crawler.thread.CrawlerTaskExecutor;

@Named
public class CityCrawlerTaskResultHandler implements CrawlerTaskResultHandler {

	private Logger logger = Logger.getLogger(CityCrawlerTaskResultHandler.class);

	@Inject
	@Named("summaryTotalPageCrawlerTaskExecutor")
	private CrawlerTaskExecutor taskExecutor;

	@Override
	public void handle(CrawlerTask<?> task) {
		try {
			CityCrawlerTask innerTask = (CityCrawlerTask) task;

			List<City> cities = innerTask.getResult();
			for (City city : cities) {
				SummaryTotalPageCrawlerTask totalPageTask = new SummaryTotalPageCrawlerTask();
				totalPageTask.setSource(innerTask.getSource());
				totalPageTask.setType(CrawlerTaskType.SummaryTotalPageCrawlerTask);
				totalPageTask.setCity(city);
				taskExecutor.submit(totalPageTask);
			}
		} catch (Exception ex) {
			logger.error("An error occurred while handling task result.", ex);
		}
	}

	public void setTaskExecutor(CrawlerTaskExecutor taskExecutor) {
		this.taskExecutor = taskExecutor;
	}

}
